package com.survey.Controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.survey.pojo.data.ExamAnswerVO;
import com.survey.pojo.data.QuestionBackVO;
import com.survey.pojo.data.SurveyDO;
import com.survey.pojo.data.UserDO;
import com.survey.pojo.vo.UserVO;
import com.survey.service.SurveyService;
import com.survey.utils.Result;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.awt.*;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

@Controller
public class SurveyShowController {
    Map<Integer,Map<String,String>> mapMap = new LinkedHashMap<>();

    @Autowired
    SurveyService surveyService;
    @RequestMapping("/SurveyShow")
    public String SurveyShow(Integer sid, Model model){

        QuestionBackVO back = surveyService.back(sid);
        int count = back.getSingleQuestions().size()+back.getMultiQuestions().size();
        model.addAttribute("survey",back);
        model.addAttribute("count",count);
        model.addAttribute("sid",sid);
        return "SurveyShow.jsp";
    }

    @RequestMapping("Surveysubmit")
    @ResponseBody
    public Result submit(String result, HttpSession session) throws IOException {
        UserDO userDO = (UserDO) session.getAttribute("user");

        if(userDO==null){
            return new Result(Result.CODE_FAILURE,"你未登陆,请登陆后再参与");
        }
        String replace = result.replace("\\\\", "");
        ObjectMapper obj =new ObjectMapper();
        ExamAnswerVO answerVO = obj.readValue(result, ExamAnswerVO.class);
        System.out.println(answerVO);
        return surveyService.submit(answerVO);
    }

    @RequestMapping("PrivateSurveyShow")
    public String privateSurveyShow(String sid,Model model){
        SurveyDO surveyDO = surveyService.privateSurveyShow(sid);
        if(surveyDO==null){
            return "error.jsp";
        }
        return SurveyShow(Integer.parseInt(sid),model);
    }
}
